package config

import (
	"database/sql"
	"os"
	"path/filepath"
	us "photoPlugIn/utils"
)

var CONFIG = &CF{
	PHOTODB:         "",
	PHOTOAddr:       "",
	DBType:          "",
	DBAddr:          "",
	DBName:          "",
	SEAFILEUSER:     "",
	SEAFILEPASSWD:   "",
	CacheDir:        "",
	FOLDERDir:       "",
	SimpleWebServer: false,
	WebServerRoot:   "",
}

type CF struct {
	PHOTODB         string `Notes:照片来源`
	PHOTOAddr       string `Notes:照片来源的地址`
	DBType          string `Notes:使用的数据库`
	DBAddr          string `Notes:数据库地址`
	DBName          string `Notes:数据库名称`
	SEAFILEUSER     string `Notes:seafile用户名`
	SEAFILEPASSWD   string `Notes:seafile密码`
	FOLDERDir       string `Notes:照片来源`
	CacheDir        string `Notes:缓存地址`
	SimpleWebServer bool   `Notes:是否启用webServer`
	WebServerRoot   string `Notes:webServer路径`
	Conn            *sql.DB
}

func InitConfigInfo() {
	myConfig := new(us.Config)
	myConfig.InitConfig("config.ini")
	CONFIG = &CF{
		PHOTODB:       myConfig.Read("default", "PHOTODB"),
		PHOTOAddr:     myConfig.Read(myConfig.Read("default", "PHOTODB"), "SeafileAddr"),
		FOLDERDir:     myConfig.Read(myConfig.Read("default", "PHOTODB"), "folderDir"),
		SEAFILEUSER:   myConfig.Read(myConfig.Read("default", "PHOTODB"), "UserName"),
		SEAFILEPASSWD: myConfig.Read(myConfig.Read("default", "PHOTODB"), "Passwd"),
		DBType:        myConfig.Read("default", "DBName"),
		DBAddr:        myConfig.Read(myConfig.Read("default", "DBName"), "SqlitAddr"),
		DBName:        myConfig.Read(myConfig.Read("default", "DBName"), "SqlitDBName"),
		CacheDir:      myConfig.Read("default", "CacheDir"),
	}
	// fmt.Println(cfinfo)
	initFolder(myConfig) //初始化目录
}
func initFolder(myConfig *us.Config) {
	//初始化httpServer目录
	if myConfig.Read("default", "SimpleWebServer") == "enable" {
		CONFIG.SimpleWebServer = true
		webUrl, _ := filepath.Abs(myConfig.Read("webserver", "root"))
		if webUrl[len(webUrl)-1:] != string(os.PathSeparator) { //判断获取的文件夹后面是否有'/'
			CONFIG.WebServerRoot = webUrl + string(os.PathSeparator) //如果没有，添加'/'
		}
		// 是否有根目录地址如果没有则创建
		us.PathExists(CONFIG.WebServerRoot, true)
	}

	//初始化临时目录
	cacheDir, _ := filepath.Abs(CONFIG.CacheDir)
	if cacheDir[len(cacheDir)-1:] != string(os.PathSeparator) { //判断获取的文件夹后面是否有'/'
		cacheDir = cacheDir + string(os.PathSeparator) //如果没有，添加'/'
	}
	CONFIG.CacheDir = cacheDir
	us.PathExists(cacheDir, true)
	cacheDir = cacheDir + CONFIG.PHOTODB
	us.PathExists(cacheDir, true)
}
